<?php
/**
 * TODO: не забыть приджойнить t_acl_tree для проверки на удаление,
 * TODO: отучить от RH и store
 *
 * @package default
 * @author Alexander Sibiryakov
 **/
$this->useClass('AggregatedModel_Feed_ReaderItems');
class AggregatedModel_Feed_ReaderGallery extends AggregatedModel_Feed_ReaderItems implements AggregatedModel_Feed_FeedInterface
{
	public $rh;
	
	public function clean() {
		unset($this->items);
		unset($this->pager);
		unset($this->tag);
		unset($this->current_tdi_oid);
		unset($this->community_oid);
		$this->page_citems = 3;
		unset($this->page_number);
	}
			
	protected function fetch_posts( $q, $page_number, $struct_type )
	{ 
		// извлекает посты по where-части запроса и номеру страницы

		$where = $this->prepare_where_query(
			$this->tag,
			$this->tdis_enum,
			$this->community_oid,
			$this->filter_by_day,
			$this->user_oid,
			$this->filter_by_doctype
		);

		// извлекает посты по where-части запроса и номеру страницы
		$limit = ' limit '.($page_number-1) * $this->page_citems.','.$this->page_citems;
		if ($this->order_by) $order_by = "ORDER BY ".$this->order_by." DESC";
		else $order_by = '';
		
		$sql ="
		SELECT 
		O.*,
		istorage.oid AS image_oid
		FROM store_objects AS O 
		INNER JOIN store_class_allfeed AS allfeed ON (O.oid = allfeed.oid AND allfeed.is_deleted = 0) 
		INNER JOIN store_class_imagestorage AS istorage ON istorage.oid = allfeed.image_oid 
		$where
		$order_by
		$limit
		";
		
		$ors = new DBStoreResult($this->rh->ctx->store,
				$this->rh->ctx->store->query( $sql ));

		if (!$ors) { echo "there is no available feed for you"; return false; }
		

		$m_user = $this->rh->ctx->mm->getModel("User", "m");		
		$m_image = $this->rh->ctx->mm->getModel("Image", "m");		

		while ($obj = $ors->next()) { 
			// $obj - документ типа 'image'
			// собственно картинка содержится в объекте с oid = image_oid
		
			$row = $ors->rs->current();
			
			// найдем автора
			$user = $m_user->getUser($obj->data['posted_by_id']);
			// найдем картинку
			$image = $m_image->getImage($row['image_oid']);
			
			$item = $obj->data;
			$item['oid' ] = $obj->id;
			$item['uname'] = $user->data['fullname'];
			$item['user'] = $user->data;
			$item['user']['oid'] = $user->id;
			$item['image'] = $image->data;
			$item['image']['oid'] = $image->id;

			$items[] = $item;
			
		}
		
		return $items;
		
	}
	
} // END class 
